package org.dant.ant.extension.net.repository;

import java.util.*;

import org.dant.apache.tools.ant.taskdefs.ProcessDestroyer;
import org.dant.ant.extension.utils.StringUtils;
import org.dant.ant.extension.tasks.internal.Endpoint;

public class ProcessRepository {
  private static ProcessRepository instance = new ProcessRepository();
  private static ProcessDestroyer processDestroyer = new ProcessDestroyer();

  private Map groups = new HashMap();
  
  private ProcessRepository() {}

  public static ProcessRepository getInstance() {
    return instance;
  }

  public ProcessDestroyer getProcessDestroyer() {
    return processDestroyer;
  }

  public int getGroupSize() {
    return groups.size();
  }
  
  public ProcessGroup getProcessGroup(String processKey) {
    return (ProcessGroup) groups.get(processKey);
  }

  public void addProcessGroup(String key, ProcessGroup group) {
    groups.put(key, group);
  }

  public int getProcessCount(String key) {
    return ((ProcessGroup)groups.get(key)).getCount();
  }

  public void removeLastProcess(String key) {
    ProcessGroup group = (ProcessGroup) groups.get(key);
    group.removeLast();
  }

  public void remove(String key, Process process) {
    ProcessGroup group = (ProcessGroup) groups.get(key);
    if (group == null) return;
    if (process == null)
      group.removeAll();
    else 
      group.removeProcess(process);
  }

  public void checkProcess(String key) {
    if(groups == null || groups.size() == 0) return;
    if (getProcessCount(key) > 0) {
      System.out.println("process <" + key + "> alread exist, it will be killed first");
      removeLastProcess(key);
    }
  }

  public void removeAll() {
    for(Iterator iter=groups.keySet().iterator();iter.hasNext();) {
      String key = (String) iter.next();
      ProcessGroup group = getProcessGroup(key);
      group.removeAll();
      groups.remove(key);
    }
  }
  
  public String export() {
    StringBuffer sb = new StringBuffer();
    sb.append(StringUtils.formatln("***** Process Repository [ " + Endpoint.getLocalhost() +  " ]*****",0));

    for(Iterator iter=groups.keySet().iterator();iter.hasNext();) {
      String key = (String) iter.next();
      ProcessGroup group = (ProcessGroup) getProcessGroup(key);
      sb.append(StringUtils.formatln("***** Process Group <" + key + "> *****", 2));
      sb.append(group.export());
    }
    return sb.toString();
  }
}
